'use client';

import { useToast } from '@/hooks/use-toast';
import { authClient } from '@/lib/auth-client';
import { sendMessage } from '@/service/actions/message';
import type { Message } from '@/service/type/socket';
import { useCallback, useEffect, useState, useTransition } from 'react';
import AiReplyButton from '../shop/ai-reply-button';
import { Button } from '../ui/button';
import { Textarea } from '../ui/textarea';

export default function SendMessage({
  toId,
  messages,
}: { toId: string; messages: Message[] }) {
  const { data: session } = authClient.useSession();
  const [content, setContent] = useState('');
  const [isPending, startTransition] = useTransition();
  const { toast } = useToast();

  const onSubmit = useCallback(
    (message: string) => {
      if (!message)
        return toast({ title: '请输入消息', variant: 'destructive' });
      startTransition(async () => {
        const { error } = await sendMessage({
          toId,
          content: message,
        });
        error
          ? toast({ title: error.message, variant: 'destructive' })
          : setContent('');
      });
    },
    [toast, toId],
  );

  useEffect(() => {
    const handler = (e: KeyboardEvent) =>
      e.key === 'Enter' && onSubmit(content);
    window.addEventListener('keydown', handler);
    return () => {
      window.removeEventListener('keydown', handler);
    };
  }, [onSubmit, content]);

  return (
    <div className="flex gap-2 absolute bottom-10 w-full max-w-[500px] left-1/2 -translate-x-1/2">
      <Textarea
        onChange={(e) => setContent(e.target.value)}
        value={content}
        placeholder="请输入消息"
        className="resize-none"
      />
      {session?.user?.role === 'shop' && (
        <AiReplyButton messages={messages} onSend={onSubmit} />
      )}
      <Button disabled={isPending} onClick={() => onSubmit(content)}>
        发送
      </Button>
    </div>
  );
}
